import type { TalkItem } from '@/models/talk';
import { checkLikeStatus, deleteTalk, toggleLike } from '@/services/Talk/api';
import {
  DeleteOutlined,
  HeartFilled,
  HeartOutlined,
  MessageOutlined,
} from '@ant-design/icons';
import { Avatar, Button, Card, Image, message, Popconfirm, Space } from 'antd';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import React, { useEffect, useState } from 'react';
import TalkComment from '../TalkComment';
import styles from './index.less';

interface TalkCardProps {
  talk: TalkItem;
  currentUserId?: string;  // 改为string以支持15位临时用户ID
  onUpdate?: () => void;
}

const TalkCard: React.FC<TalkCardProps> = ({
  talk,
  currentUserId,
  onUpdate,
}) => {
  const [isLiked, setIsLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(talk.likeCount || 0);
  const [showComments, setShowComments] = useState(false);
  const [commentCount, setCommentCount] = useState(talk.commentCount || 0);
  const [animationClass, setAnimationClass] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 获取点赞状态
  const fetchLikeStatus = async () => {
    if (!currentUserId) return;

    try {
      const result = await checkLikeStatus(talk.id, currentUserId);
      if (result && result.code === 200) {
        setIsLiked(result.data || false);
      }
    } catch (error) {
      console.error('获取点赞状态失败:', error);
    }
  };

  // 组件挂载时获取点赞状态
  useEffect(() => {
    fetchLikeStatus();
  }, [talk.id, currentUserId]);

  // 处理点赞（支持临时用户）
  const handleLike = async () => {
    if (!currentUserId) {
      message.warning('用户ID获取失败，请刷新页面');
      return;
    }

    // 保存当前状态用于错误回滚
    const previousIsLiked = isLiked;
    const previousLikeCount = likeCount;

    try {
      // 调用后端API
      const result = await toggleLike(talk.id, currentUserId);

      // 根据后端返回的数据结构解析点赞状态
      let actualIsLiked;
      if (
        result.data &&
        typeof result.data === 'object' &&
        'newIsLiked' in result.data
      ) {
        actualIsLiked = result.data.newIsLiked;
      } else {
        actualIsLiked = result.data;
      }

      // 确保状态与后端返回一致
      setIsLiked(actualIsLiked);

      // 根据状态变化更新点赞数量
      if (actualIsLiked !== previousIsLiked) {
        setLikeCount(
          actualIsLiked ? previousLikeCount + 1 : previousLikeCount - 1,
        );
      }

      // 更新提示信息
      if (actualIsLiked) {
        setAnimationClass('heartbeat');
        message.success('点赞成功 ❤️');
      } else {
        setAnimationClass('unliked');
        message.success('取消点赞');
      }

      // 清除动画类名
      setTimeout(() => {
        setAnimationClass('');
      }, 600);
    } catch (error) {
      console.error('点赞操作失败:', error);
      // 回滚到之前的状态
      setIsLiked(previousIsLiked);
      setLikeCount(previousLikeCount);
      message.error('点赞操作失败，请重试');
    }
  };

  // 处理删除
  const handleDelete = async () => {
    if (!currentUserId) {
      message.warning('无法获取用户信息');
      return;
    }
    
    setDeleteLoading(true);
    try {
      const result = await deleteTalk(talk.id, currentUserId);
      if (result.code === 200) {
        message.success('删除成功');
        onUpdate?.();
      }
    } catch (error) {
      message.error('删除失败，请重试');
    } finally {
      setDeleteLoading(false);
    }
  };

  // 处理评论数更新
  const handleCommentUpdate = () => {
    setCommentCount((prev) => prev + 1);
    onUpdate?.();
  };

  // 格式化时间
  const formatTime = (timeStr: string) => {
    try {
      const time = new Date(timeStr);
      return formatDistanceToNow(time, {
        addSuffix: true,
        locale: zhCN,
      });
    } catch {
      return timeStr;
    }
  };

  // 解析图片列表
  const getImageList = () => {
    // 优先使用后端处理好的imageList字段（包含带签名的OSS URL）
    if (talk.imageList && Array.isArray(talk.imageList)) {
      return talk.imageList;
    }

    // 如果没有imageList，则尝试解析原始的images字段（向后兼容）
    if (!talk.images) return [];

    try {
      // 尝试解析JSON格式的图片数据
      const parsed = JSON.parse(talk.images);
      return Array.isArray(parsed) ? parsed : [];
    } catch (error) {
      const result = talk.images.split(',').filter((img) => img.trim());
      return result;
    }
  };

  const imageList = getImageList();
  const isOwner = currentUserId === talk.userId;

  return (
    <Card className={styles.talkCard}>
      <div className={styles.cardHeader}>
        <Space>
          <Avatar
            src={talk.avatar || require('@/assets/images/post.png')}
            size={48}
            className={styles.avatar}
          />
          <div className={styles.userInfo}>
            <div className={styles.username}>{talk.username || '匿名用户'}</div>
            <div className={styles.time}>{formatTime(talk.createTime)}</div>
          </div>
        </Space>

        {isOwner && (
          <Popconfirm
            title="确定要删除这条说说吗？"
            onConfirm={handleDelete}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              icon={<DeleteOutlined />}
              loading={deleteLoading}
              className={styles.deleteBtn}
              danger
            />
          </Popconfirm>
        )}
      </div>

      <div className={styles.content}>
        <p className={styles.text}>{talk.content}</p>

        {/* 图片展示 */}
        {imageList.length > 0 && (
          <div className={styles.imageGrid}>
            <Image.PreviewGroup>
              {imageList.map((image, index) => (
                <div key={index} className={styles.imageWrapper}>
                  <Image
                    src={image.trim()}
                    alt={`图片${index + 1}`}
                    className={styles.image}
                    fallback={require('@/assets/images/post.png')}
                  />
                </div>
              ))}
            </Image.PreviewGroup>
          </div>
        )}
      </div>

      <div className={styles.actions}>
        <Space size={24}>
          <Button
            type="text"
            icon={isLiked ? <HeartFilled /> : <HeartOutlined />}
            onClick={handleLike}
            className={`${styles.actionBtn} ${isLiked ? styles.liked : ''} ${
              animationClass ? styles[animationClass] : ''
            }`}
          >
            {likeCount}
          </Button>

          <Button
            type="text"
            icon={<MessageOutlined />}
            onClick={() => setShowComments(!showComments)}
            className={`${styles.actionBtn} ${
              showComments ? styles.active : ''
            }`}
          >
            {commentCount}
          </Button>
        </Space>
      </div>

      {/* 评论区域 */}
      {showComments && (
        <div className={styles.commentSection}>
          <TalkComment
            talkId={talk.id}
            currentUserId={currentUserId}
            onCommentAdd={handleCommentUpdate}
          />
        </div>
      )}
    </Card>
  );
};

export default TalkCard;
